import tvrage, showdb
import re, datetime, time

from sqlobject import SQLObjectNotFound

RE_EPISODE_P = re.compile("(\d+)x(\d+)")

showdb.init()

def _get_episode(show, season, episode_number):
	for ep in season.episodes:
		if ep.number == episode_number:
			return ep

	data = tvrage.read(show = show.name, ep = '%02dx%02d' % (season.number, episode_number))
	if not data or not data.has_key('Episode Info'):
		#~ print "NO DATA", show.name, season.number, episode_number, data
		return None
	title, date = tvrage.get_episode_info(data)
	return showdb.Episode(season = season, number = episode_number,
		title = title, date = date)


def _get_season(show, season_number):
	season = None
	for s in show.seasons:
		if s.number == season_number:
			season = s
	if not season:
		season = showdb.Season(show = show, number = season_number)

	episode_number = 1
	while True:
		result = _get_episode(show, season, episode_number)
		if result:
			episode_number += 1
		else:
			break
	print show.name, season_number, episode_number - 1
	return season

def _get_show(show_name):
	data = tvrage.read(show = show_name)
	if data:
		name = data['Show Name']
		assert name
		try:
			show = showdb.Show.byName(name)
		except SQLObjectNotFound:
			show = showdb.Show(name = name)
			show.country = data.get('Country')
			show.status = data.get('Status')
			show.classification = data.get('Classification')
			show.genres = data.get('Genres')
			show.network = data.get('Network')
			show.airtime = data.get('Airtime')
			runtime = data.get('Runtime')
			if runtime:
				show.runtime = int(runtime)

		if name != show_name:
			try:
				showdb.ShowAlternateNames(name = show_name, show = show)
			except:
				pass
		if data.has_key('Latest Episode'):
			m = RE_EPISODE_P.match(data['Latest Episode'][0])
			last_season = int(m.group(1))
			for season in range(last_season):
				_get_season(show, season + 1)
	else:
		print "SHOW NOT FOUND", show

def main():
	import sys
	if len(sys.argv) > 1:
		for show in sys.argv[1:]:
			_get_show(show)
	else:
		for show in tvrage.SHOWS:
			_get_show(show)

if __name__ == '__main__':
	main()
